package com.transfiguro.parser;

import com.transfiguro.datamodel.javamodels.ClassModel;
import com.transfiguro.visitors.ClassVisitor;
import japa.parser.JavaParser;
import japa.parser.ParseException;
import japa.parser.ast.CompilationUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * This class provides functions to parse a given {@link CompilationUnit} and build
 * datamodels out of it
 */
public class CoreParser {
    private final Logger logger = LoggerFactory.getLogger(CoreParser.class);
    private CompilationUnit compilationUnit;

    /**
     * Constructor
     *
     * @param file The file to convert
     */
    public CoreParser(final File file) {
        init(file);
    }

    /**
     * This method takes a <code>file</code> and produces the compilation unit
     * by parsing it
     *
     * @param file the file from which <code>compilationunit</code> has to be produced
     */
    private void init(final File file) {
        try {
            final FileInputStream fileInputStream = new FileInputStream(file);
            this.compilationUnit = JavaParser.parse(fileInputStream);
        } catch (final FileNotFoundException e) {
            logger.debug("Exception: {}", e.getMessage());
        } catch (final ParseException e) {
            logger.debug("Exception: {}", e.getMessage());
        }
    }

    /**
     * This method builds a {@link ClassModel} out of the <code>compilationunit</code>
     *
     * @return The <code>ClassModel</code> built by going through everything in the input Java file
     */
    public ClassModel parse() {
        ClassModel model;
        ClassVisitor classVisitor = new ClassVisitor(compilationUnit);
        classVisitor.visit(compilationUnit, null);
        model = classVisitor.getModel();
        return model;
    }

}
